from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from myadmin import models




def cartadd(request):
    gid = request.GET['gid']
    num = int(request.GET['num'])

    # 获取商品id和购买数量
    ob = models.Goods.objects.get(id=gid)
    # 构造字典
    goods = {'gid':ob.id,'title':ob.title,'price':ob.price,'pic':ob.pic,'num':num}
    # 获取购物车数据,如果没有则返回空字典
    data = request.session.get('Cart',{})
    # 判断商品是否已经存在购物车中
    if gid in data:
        data[gid]['num'] += num
    else:
        data[gid] = goods
    # 数据重新存入购物车
    request.session['Cart'] = data
    return JsonResponse({'error':0,'msg':'加入购物车成功'})



def cartindex(request):
    return render(request,'home/cart/index.html')




def cartclear(request):
    # 清空cart的值
    request.session['Cart'] = {}
    return HttpResponse('cartclear')

'''
HttpResponse    返回字符串类型数据
JsonResponse    返回字典类型的数据
'''


def cartdelete(request,gid):
    # 删除购物车中制定id的商品
    data = request.session.get('Cart',{})
    del data[gid]
    # 把修改后的数据重新存到session中
    request.session[Card] = data
    return HttpResponse("<script>location.href='%s'</script>"%(reverse('myhome_cartindex')))





def cartedit(request):
    # get方法传送了id和num的数据
    gid = request.GET.get('gid')
    num = int(request.GET.get('num'))
    # 获取当前购物车数据
    data = request.session['Cart']
    # 修改购买的数量
    data[gid]['num'] = num
    # 更新session
    data = request.session['Cart'] = data
    return HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')



def orderconfirm(request):
    # ids  商品的id
    ids = request.GET.get('ids')
    # print(ids)   # eg : [2,3,6...]
    ids = ids.split(',')
    # 使用get获取的id去session中查询数量
    cart = request.session.get('Cart')
    data = {}
    for x in ids:
        # get中的id为键，session中的id对应的个数为值
        data[x] = cart[x]
    # 获取id对应用户的所有收获地址(地址的id作为外键和Users数据库对应)
    adds = models.Address.objects.filter(uid = request.session['VipUser']['uid'])
    # data = {id: message }
    context = {'data':data,'adds':adds}
    return render(request,'home/order/confirm.html',context)


def ordercreate(request):
    #接收数据(商品的id)
    ids = request.POST.get('ids')
    ids = ids.split(',')
    # 地址 addid
    addid = request.POST.get('addid')

    # 生成订单
    orderdata = {}
    orderdata['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])
    orderdata['aid'] = models.Address.objects.get(id=addid)
    orderdata['totalprice'] = 0
    ob = models.Order.objects.create(**orderdata)

    # 获取购物车数据
    cart  =request.session['Cart']
    totalprice = 0
    # 订单详情
    for x in ids:
        res = models.OrderInfo()
        res.orderid = ob
        # 购买的商品详情
        goods = models.Goods.objects.get(id=x)
        res.goodsid = goods
        res.price = goods.price
        res.num = cart[x]['num']
        res.save()
        # 删除购物车中已经购买的商品
        del cart[x]
        # 计算总价
        totalprice += res.price*res.num
        # 扣除库存
        goods.num -= res.num
        goods.save()
        # 同步购物车数据到session数据表中
    request.session['Cart'] = cart
    ob.totalprice = totalprice
    ob.save()

    # 跳转支付页面s
    return HttpResponse('<script>alert("请支付");location.href="/order/buy/'+str(ob.id)+'/"</script>')



# 添加收货地址
def addressinsert(request):
    '''
    
    先创建字典类型的对象data;再使用create(**data)   对数据库进行添加
    :param request: 
    :return: 
    '''
    # reveive data
    data = request.GET.dict()
    # acquire userobject
    data['uid'] = models.Users.objects.get(id = request.session['VipUser']['uid'])
    # //判断新加地址是否是默认值
    if data['status'] == '1':
        data['status'] = True
        # //把以前的地址全部修改为非默认
        obs = models.Address.objects.filter(uid=data['uid'])
        for i in obs:
            i.status = False
            i.save()
    # //执行添加
    ob = models.Address.objects.create(**data)
    return JsonResponse({'error':0,'msg':'地址添加成功'})




def orderbuy(request,oid):
    # 用订单id获取订单信息
    ob = models.Order.objects.get(id = oid)
    context = {'order':ob}
    # 显示支付页面
    return render(request,'home/order/buy.html',context)






def orderbuysuccess(request,oid):
    # 根据订单id获取订单信息
    ob = models.Order.objects.get(id = oid)
    ob.status = 1
    ob.save()
    return render(request,'home/order/success.html')








def myorder(request):
    # 获取当前用户的所有订单
    orderlist = models.Order.objects.filter(uid=request.session['VipUser']['uid'])
    context = {'orderlist':orderlist}

    return render(request,'home/center/myorder.html',context)















